package com.vincce.fitness.core.util;

import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;

import java.io.Writer;

/**
 * Created with IntelliJ IDEA.
 * User: henry
 * Date: 8/15/13
 * Time: 1:32 PM
 * To change this template use File | Settings | File Templates.
 */
public class CDataXppDriver extends DomDriver {

	public CDataXppDriver(String encoding) {
		super(encoding);
	}

	@Override
	public HierarchicalStreamWriter createWriter(Writer out) {
		return new PrettyPrintWriter(out){

			boolean cdata = false;

			@Override
			public void startNode(String name, Class clazz) {
				super.startNode(name, clazz);
				cdata = clazz == String.class;
			}

			@Override
			public void setValue(String text) {
				super.setValue(text);
			}

			@Override
			protected void writeText(QuickWriter writer, String text) {
				if(cdata){
					writer.write("<![CDATA[");
					writer.write(text);
					writer.write("]]>");
				}else {
					writer.write(text);
				}
			}
		};
	}
}
